package soap;

import com.sun.xml.internal.messaging.saaj.soap.impl.TextImpl;
import org.w3c.dom.Node;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;

public class SoapCommand {

    public static void main(String[] args) throws SOAPException, MalformedURLException {
        SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
        SOAPMessage message = MessageFactory.newInstance().createMessage();

        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();

        QName qName = new QName("urn:MaNGOS","executeCommand");
        SOAPBodyElement soapBodyElement = body.addBodyElement(qName);
        soapBodyElement.addChildElement("command").addTextNode(".account");

        URL u = new URL("http://admin:admin@127.0.0.1:7878");
        SOAPMessage call = connection.call(message, u);

        System.out.println(firstChild(call.getSOAPPart().getEnvelope().getBody()));
        System.out.println("done!");
    }

    private static String firstChild(Node node){
        if (node instanceof TextImpl){
            return  ((TextImpl) node).getData();
        }
        if (Objects.isNull(node.getFirstChild())){
            return null;
        }
        return firstChild(node.getFirstChild());
    }

}
